var httpRequest = require('wxRequest.js');
var config = require('config.js');

function checkUserLogin(func) {
  //wxLogin();
  wx.checkSession({
    success: function () {
      var userInfo = getUserInfo(wx.getStorageSync('3rd_session'), func);
    },
    fail: function () {
      wxLogin(func);
    }
  });
}

function wxLogin(sucfunc) {
  //调用登录接口
  //1.小程序调用wx.login得到code.
  wx.login({
    success: function (res) {
      var code = res['code'];

      if (res.code) {
        //这里是干什么用的
        wx.request({
          url: 'http://mp.jgmyxy.com/api/get_weixin',  // “http://mp.jgmyxy.com/api/add_user” 这两个api多余了，  登陆和添加用户同时进行
          data: {
            code: res.code
          },
          method: "POST",
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            console.log("获取code -> 后台 判断是否登录, openid: " + res.data.data.openid)
            wx.setStorageSync('openid', res.data.data.openid)
          }
        })
      } else {
        console.log('微信自身登录失败！' + res.errMsg)
      }

      //2.小程序调用wx.getUserInfo得到rawData, signatrue, encryptData.
      wx.getUserInfo({
        success: function (info) {
          //console.log(info);
          var rawData = info['rawData'];
          var signature = info['signature'];
          var encryptData = info['encryptData'];
          var encryptedData = info['encryptedData']; //注意是encryptedData不是encryptData...坑啊
          var iv = info['iv'];

          var param = {
            token: config.token,
            "code": code,
            "rawData": rawData,
            "signature": signature,
            'iv': iv,
            'encryptedData': encryptedData,
          };
          var uri = config.apiUrl + config.actionUserLogin;
          //3.小程序调用server获取token接口, 传入code, rawData, signature, encryptData.
          wx.request({
            url: uri,
            data: param,
            method: 'POST',
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: (res) => {
              var data = JSON.parse(res.data.trim());
              wx.setStorageSync("3rd_session", data.info.session_id);
              typeof sucfunc == "function" && sucfunc(data.info, "");
            },
            fail: (err) => {
              console.log("用户登录失败, http请求:" + uri);
              console.log(err);
            }
          });
        }
      });

    }
  });
}

function getUserInfo(sessionId, func) {
  var param = { token: config.token, sessionId: sessionId };
  httpRequest.wxRequest(config.apiUrl, config.actionUserLogin, param, function (res) {
    typeof func == "function" && func(res.info, "");
  }, function () {
    console.log("用户登录失败, http请求:" + uri);
    return;
  }
  );
}

module.exports = {
  checkUserLogin: checkUserLogin
}